package com.yingsheng.bi.hks.config.props;

import lombok.Data;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Data
public class ChannelSmsProperties {

    private Long defaultTimeout;

    private Boolean sendLimitCheck = true;

    private Map<String, Long> expireMapping = new HashMap<>();

    private Map<String, String> templateIdMapping = new HashMap<>();

    private Map<String, SmsProperties> channelMapping = new HashMap<>();

    public SmsProperties getSmsProperties(String channel) {
        if (StringUtils.hasText(channel) && !CollectionUtils.isEmpty(this.channelMapping)) {
            return this.channelMapping.get(channel);
        }
        return null;
    }

    /**
     * 短信发送频率控制开关
     * 注意：优先级是全局大于局部开关
     *
     * @param channel 渠道标识
     * @return 短信发送频率控制开关是否开启, true-开启即要校验, false-关闭即不校验
     */
    public boolean sendLimitCheck(String channel) {
        if (this.sendLimitCheck && StringUtils.hasText(channel)) {
            SmsProperties smsProperties = getSmsProperties(channel);
            if (smsProperties != null) {
                return smsProperties.getSendLimitCheck();
            }
        }
        return this.sendLimitCheck;
    }

    public Long getExpireTime(String channel, String key) {
        if (StringUtils.hasText(channel)) {
            SmsProperties smsProperties = getSmsProperties(channel);
            if (smsProperties != null) {
                Long timeout = smsProperties.getExpireTime(key);
                if (timeout != null) {
                    return timeout;
                }
            }
        }
        if (StringUtils.hasText(key) && !CollectionUtils.isEmpty(this.expireMapping)) {
            Long timeout = this.expireMapping.get(key);
            if (timeout != null) {
                return timeout;
            }
        }
        return this.defaultTimeout;
    }

    public String getTemplateId(String channel, String key) {
        if (StringUtils.hasText(channel)) {
            SmsProperties smsProperties = getSmsProperties(channel);
            if (smsProperties != null) {
                String templateId = smsProperties.getTemplateId(key);
                if (StringUtils.hasText(templateId)) {
                    return templateId;
                }
            }
        }
        if (StringUtils.hasText(key) && !CollectionUtils.isEmpty(this.templateIdMapping)) {
            String templateId = this.templateIdMapping.get(key);
            if (StringUtils.hasText(templateId)) {
                return templateId;
            }
        }
        return null;
    }

}
